<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends User_Controller
{
	private $response = array();
	private $userModel;
	private $clientModel;
	private $requestManager;
	private $settings;
    public function __construct()
    {
        parent::__construct();
        $this->userModel = $this->load->model('User_Model');
        $this->clientModel = $this->load->model('Client_Model');
        $this->requestManager = RequestManager::getInstance();
        $this->settings = $this->config->item('settings');
        $this->load->library('session');
        $allowed = array('index','login','logout');
        $this->load->helper('ConstantsUtils');
        if(!in_array($this->router->fetch_method(), $allowed)) {
	        if(isset($this->session) && !$this->session->userdata('isLogged')) {
	        	redirect('/');
	        }
        }
        
        
    }

    public function index(){
    	if(isset($this->session) && $this->session->userdata('isLogged')){
    		redirect('user/file201');
    	} else {
    		$this->login();
    	}

    }
	public function login(){
		$this->load->helper(array('form', 'url'));
		$this->load->library('form_validation');

		$this->form_validation->set_rules('username', 'Username', 'required');
		$this->form_validation->set_rules('password', 'Password', 'required');	
		
		$data = array();
		if($this->input->post() && $this->form_validation->run() != FALSE ){	
				
			
			$username = urldecode($this->input->post('username'));
			$password = urldecode($this->input->post('password'));

			// Model Call
			/*
			if($this->userModel->login($username,$password)){
				redirect("user/profile");
			}else {
				redirect("/");
			}
			*/
			
			// API CALL
			$this->requestManager->setData(array('username'=>urlencode($username),'password'=>$password));
			$this->requestManager->setSendType("rest");
			$this->requestManager->setAccessPath($this->settings['api_path']."user/login/" .$this->settings['client_key']);
			$return = $this->requestManager->send();
			//var_dump($return);
			if(isset($return)){
				if($return->message == 'success'){
					$this->userModel->saveSession($return->data);
					redirect("user/file201");
				} else {
					$this->session->set_userdata('error_message', 'Username and password are mismatched!');
					redirect("/");
				}
			}
			
			
			
			
		//	$url = $this->settings['api_path'] ."user/register/" . $this->settings['client_key']."/$username/$password";
		//	$json = file_get_contents($url);
		//	$array = json_decode($json);
			
			#$data['message'] = $array->message;
			//var_dump($array);
			
						
			// get all users...
		/*	$url = $this->settings['api_path'] ."user/all_users/". $this->settings['client_key'];
			$json = file_get_contents($url);
			$response = json_decode($json);
			if(!empty($response))
			$data['users'] = $response->data;
			$this->load->view('user',$data);
		*/	
		
		}else{			
			//if($this)
			$error_message = $this->session->userdata('error_message');
			$setting = array('login'=>true);
			$this->load->view('header',$setting);
			$this->load->view('user');
			$this->load->view('footer');
		}
	}
	
	public function uploadPicture(){
		$error = array('error'=>"");
		//var_dump($this->input->post('userfile'));
		if($this->input->post()){
			//echo "test";
			//var_dump ($this->input->post('userfile'));
			$config['upload_path'] = './uploads/';
			$config['allowed_types'] = 'gif|jpg|png';
			$config['max_size']	= '100';
			$config['max_width']  = '1024';
			$config['max_height']  = '768';
			
			$user_id = $this->input->post('user_id');
			$config['file_name']  = "$user_id"."_".time();
	
			$this->load->library('upload', $config);
			//$this->upload->initialize($config);
	
			if ( ! $this->upload->do_upload())
			{
				$error = array('error' => $this->upload->display_errors());
				$data['message'] = $error;
			}
			else
			{
				//var_dump($this->upload->data());
				
				$info = array('upload_data' => $this->upload->data());
				$this->requestManager->setData(array('photo'=>$info['upload_data']['file_name'],'user_id'=>$user_id));
				$this->requestManager->setSendType("post");
				$this->requestManager->setAccessPath($this->settings['api_path']."user/uploadPicture/" .$this->settings['client_key']);
				$return = $this->requestManager->send();
				if(isset($return)){
					if($return->message == 'success'){
						$data['message']="Image successfully uploaded!";
						$data['success'] = 1;
						$data['new_photo'] = $info['upload_data']['file_name'];
						// delete previous photo;
						if($this->input->post('old_photo') != ''){
							//$this->load->helper('FileUtils');
							$old_photo = $_SERVER['DOCUMENT_ROOT'].'/uploads/'.$this->input->post('old_photo');
							$data['old_photo'] = $old_photo;
							unlink($old_photo);
							//$this->FileUtils->deleteFile($old_photo);
						}
						
						
					} else {
						$data['message']="error";
					}
				}
				//$this->load->view('upload_success', $data);
				//update api profile image.
			}
			$this->load->view('upload_success', $data);
		} else {
			$this->load->view('upload_form', $error);
		}
	}
	
	public function addUser(){
	
		$this->load->helper(array('form', 'url'));
		$this->load->library('form_validation');
		$this->load->helper('email');
		
		$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|matches[confirm_password]|min_length[6]');
		$this->form_validation->set_rules('confirm_password', 'Password Confirmation', 'trim|required');

		if ($this->form_validation->run() != FALSE )
		{
			$data['username'] = urlencode($this->input->post('email'));
			$data['password'] = $this->input->post('password'); //CommonUtils::encryptPassword($this->input->post('password'));
			//$data['is_active'] = 1;
			$data['client_id'] = $this->session->userdata('client_id');
			$data['status'] = 0;
			
			/* Model call
			$user_id = $this->userModel->save($data);
			redirect("user/display_members/$user_id");
			*/
			// API CALL
			$this->requestManager->setData(array('username'=>$data['username'],'password'=>$data['password']));
			$this->requestManager->setSendType("rest");
			$this->requestManager->setAccessPath($this->settings['api_path']."user/register/" .$this->settings['client_key']);
			$return = $this->requestManager->send();
			if($return->message == 'success'){
				redirect("user/display_members/" . $return->data->user_id);
			} 
			
			
		}
				
		$this->load->view('header');
		$this->load->view('adduser');
		$this->load->view('footer');
	}
	
	/*
	 * Note: Working on DB kindly comment API call. 
	 */
	
	public function display_members(){
	
		// Model call
		//$data['users'] = $this->userModel->getAllUsers();
		
		// API call
		$this->requestManager->setSendType("rest");
		$this->requestManager->setAccessPath($this->settings['api_path']."user/display_members/" .$this->settings['client_key']);
		$return = $this->requestManager->send();
		$data['users'] = $return->data;
		//echo $this->session->userdata('isSuperAdmin')?'1':'0';
		$this->load->view('header');
		$this->load->view('display_users', $data);
		$this->load->view('footer');
	}
	
	public function profile(){		
		$data['users'] = $this->userModel->getUserProfile($this->session->userdata('client_id'));
		$this->load->view('header');
		$this->load->view('profile', $data);
		$this->load->view('footer');
	}
	
	public function file201($user_id = 0){
		
		if($user_id <=0) $user_id = $this->session->userdata('user_id');
		$data = array();
		//var_dump($this->session->userdata);
		if($this->input->post()){
			
			$data['user_id']= $this->input->post('user_id');			
			$data['first_name']= $this->input->post('first_name');
			$data['last_name']= $this->input->post('last_name');
			$data['middle_name']= $this->input->post('middle_name');
			$data['present_address']= $this->input->post('present_address');
			$data['home_address']= $this->input->post('home_address');
			$data['home_phone']= $this->input->post('home_phone');
			$data['gender']= $this->input->post('gender');
			$data['mobile_phone']= $this->input->post('mobile_phone');
			$data['spouse_last_name']= $this->input->post('spouse_last_name');
			$data['spouse_first_name']= $this->input->post('spouse_first_name');
			$data['spouse_middle_name']= $this->input->post('spouse_middle_name');
			$data['notify_person']= $this->input->post('notify_person');
			$data['notify_phone']= $this->input->post('notify_phone');
			$data['notify_mobile_phone']= $this->input->post('notify_mobile_phone');
			$data['tin']= $this->input->post('tin');
			$data['sss']= $this->input->post('sss');
			$data['philhealth']= $this->input->post('philhealth');
			$data['pag_ibig']= $this->input->post('pag_ibig');
			$data['blood_type']= $this->input->post('blood_type');
			$data['employee_id']= $this->input->post('employee_id');
			$data['birth_date']= $this->input->post('birth_date');
			$data['employee_type']= $this->input->post('employee_type');
			
			
			// Model call
			//$this->userModel->saveUserProfile($data);
			
			// API CALL
			$this->requestManager->setData($data);
			$this->requestManager->setSendType("post");
			$this->requestManager->setAccessPath($this->settings['api_path']."user/file201/" .$this->settings['client_key']);
			$return = $this->requestManager->send();
			
			//var_dump($return);
			//die();

			/* api call
			$this->requestManager->setData($data);
			$this->requestManager->setSendType("post");
			$this->requestManager->setAccessPath($this->settings['api_path']."user/file201/" .$this->settings['client_key']);
			$return = $this->requestManager->send();
			*/
			

		}
		//$data['user'] = $this->userModel->getUserProfile($user_id);
		// Get file 201
		$this->requestManager->setData(array('user_id'=>$user_id));
		$this->requestManager->setSendType("rest");
		$this->requestManager->setAccessPath($this->settings['api_path']."user/getProfile/" .$this->settings['client_key']);
		$return = $this->requestManager->send();
		if($return->message =='success'){
			$data['user'] = $return->data;
		}

		// Get Dependents
		$this->requestManager->setData(array('user_id'=>$user_id));
		$this->requestManager->setSendType("rest");
		$this->requestManager->setAccessPath($this->settings['api_path']."user/getDependents/" .$this->settings['client_key']);
		$return = $this->requestManager->send();
		if($return->message =='success'){
			$data['dependents'] = $return->data;
		}
		
		// Get Employment
		$this->requestManager->setData(array('user_id'=>$user_id));
		$this->requestManager->setSendType("rest");
		$this->requestManager->setAccessPath($this->settings['api_path']."user/getEmployment/" .$this->settings['client_key']);
		$return = $this->requestManager->send();
		if($return->message =='success'){
			$data['employment'] = $return->data;
			
		}
		
		$data['education'] = $this->userModel->getEducation($user_id);		
		//$data['dependents'] = $this->userModel->getDependents($user_id);
		//$data['employment'] = $this->userModel->getEmployment($user_id);		
		
		
		// Get Salary
		$this->requestManager->setData(array('user_id'=>$user_id));
		$this->requestManager->setSendType("rest");
		$this->requestManager->setAccessPath($this->settings['api_path']."user/get_salary/" .$this->settings['client_key']);
		$return = $this->requestManager->send();
		if(isset($return)){
			if($return->message =='success'){
				$data['salary'] = $return->data;
				
			}
			
		}
		
		// Get Contributions
		$this->requestManager->setData(array('user_id'=>$user_id));
		$this->requestManager->setSendType("rest");
		$this->requestManager->setAccessPath($this->settings['api_path']."user/get_contributions/" .$this->settings['client_key']);
		$return = $this->requestManager->send();
		if(isset($return)){
			if($return->message =='success'){
				$data['contributions'] = $return->data;
			}
			
		}
		
		$data['user_id']= $user_id;	
	
		
		$this->load->view('header');
		$this->load->view('file201',$data);
		$this->load->view('footer');
	}
	
	public function view($user_id){
	
		$data = array();
		if(is_numeric($user_id)){
			$data['user'] = $this->userModel->getUserProfile($user_id);
		}
		
		$data['user_id']= $user_id;	
		$this->load->view('header');
		$this->load->view('view',$data);
		$this->load->view('footer');
	}

	function logout(){
		$this->session->sess_destroy();
		redirect('/');
	}
	
	public function salary(){
		$data = array();
		if($this->input->post()){
			$data['monthly'] = $this->input->post('monthly');
			$data['daily'] = trim($this->input->post('daily'));
			if(isset($data['daily']) && is_numeric($data['daily'])) {
				$data['hourly'] = floatval($data['daily']) / ConstantsUtils::$EMPLOYEE_REGULAR_HOURS;
			}
			$data['user_id'] = $this->input->post('user_id');
			
			$this->requestManager->setData($data);
			$this->requestManager->setSendType("post");
			$this->requestManager->setAccessPath($this->settings['api_path']."user/salary/" .$this->settings['client_key']);
			$return = $this->requestManager->send();
			//var_dump($return);
			if ($return->message == 'success') {
				$data["message"] = "Salary successfully saved!";
			}
		}
		$this->load->view('success', $data);
		//$this->load->view('header');
		//$this->load->view('file201',$data);
		//$this->load->view('footer');
	}

	public function dependents($user_id=0){
		//echo $this->input->post('user_id');
		$data = array();
		$data['user_id'] = ($user_id < 1) ? $this->input->post('user_id'):$user_id;
		if($this->input->post()){
			$data['dependents']= array('first_name' => $this->input->post('dependent_first_name'),
			'last_name' => $this->input->post('dependent_last_name'),
			'middle_name' => $this->input->post('dependent_middle_name'),
			'type' => $this->input->post('dependent_type'),
			'id' => $this->input->post('dependent_id'),
			'gender' => $this->input->post('dependent_gender'),
			'birth_date' => $this->input->post('dependent_birth_date'));
			$data['user_id'] = $this->input->post('user_id');
			//$this->userModel->saveDependents($data);

			$params['data'] = urlencode(ObjectUtils::arrayToJSON($data));

			$this->requestManager->setData($params);
			$this->requestManager->setSendType("post");
			$this->requestManager->setAccessPath($this->settings['api_path']."user/dependent/" .$this->settings['client_key']);
			$return = $this->requestManager->send();
			//var_dump($return);
			if($return->message == 'success'){
				$data['message'] = "Dependents successfully added!";
				$fname = $this->input->post('dependent_first_name');
				$mname = $this->input->post('dependent_middle_name');
				$lname = $this->input->post('dependent_last_name');
				$birth_date = $this->input->post('dependent_birth_date');
				$gender = $this->input->post('dependent_gender');
				$type = $this->input->post('dependent_type');
				$id = $return->id;
				if(isset($fname)) $full_name = $fname[0];
				if(isset($mname)) $full_name .= ' '. $mname[0];
				if(isset($lname)) $full_name .= ' '. $lname[0];
				$data['dependent'] = array('full_name'=>$full_name, 'birth_date'=>$birth_date[0],
				'gender'=>$gender[0], 'type'=>$type[0],'id'=>$id);
				//var_dump($data);
				
			}
			
		}
		//$this->load->view('header');
		//$this->load->view('file201',$data);
		//$this->load->view('footer');
		
		$this->load->view('lightbox_header');
		$this->load->view('dependent',$data);
		$this->load->view('lightbox_footer');
	}
	
	public function edit_dependent($user_id, $id){
		if(is_numeric($user_id) && is_numeric($id)){
			
			
			if($this->input->post()){
				$data['dependents']= array('first_name' => $this->input->post('dependent_first_name'),
				'last_name' => $this->input->post('dependent_last_name'),
				'middle_name' => $this->input->post('dependent_middle_name'),
				'type' => $this->input->post('dependent_type'),
				'id' => $this->input->post('dependent_id'),
				'gender' => $this->input->post('dependent_gender'),
				'birth_date' => $this->input->post('dependent_birth_date'));
				$data['user_id'] = $this->input->post('user_id');
				$params['data'] = urlencode(ObjectUtils::arrayToJSON($data));
				//var_dump($data);
				//die();
				$this->requestManager->setData($params);
				$this->requestManager->setSendType("post");
				$this->requestManager->setAccessPath($this->settings['api_path']."user/dependent/" .$this->settings['client_key']);
				$method = 'update';
			} else {
				$params = array('user_id'=>$user_id, 'id'=>$id );
				$this->requestManager->setData($params);
				$this->requestManager->setSendType("rest");
				$this->requestManager->setAccessPath($this->settings['api_path']."user/get_dependent/" .$this->settings['client_key']);
				$method = 'edit';
			}

			$return = $this->requestManager->send();
			//var_dump($return);
			if($return->message == 'success'){
				if($method == 'edit')
					$data['dependent'] = $return->data;	
				elseif($method == 'update'){
					$data['message'] = "Dependent successfully updated!";
					//var_dump($data['dependents']);
					
					//$data['dependent'] = $data['dependents'];
					
				}
			}
			$data['user_id'] = $user_id;
			$data['depId'] = $this->input->post('dependent_id');
		}
		
		$this->load->view('lightbox_header');
		$this->load->view('edit_dependent',$data);
		$this->load->view('lightbox_footer');
		
	}
	
	public function delete_dependent(){
		$data = array();
		if($this->input->post()){
			$params = array('user_id' => $this->input->post('user_id'),
				'id' => $this->input->post('id'));
			
			$this->requestManager->setData($params);
			$this->requestManager->setSendType("rest");
			$this->requestManager->setAccessPath($this->settings['api_path']."user/delete_dependent/" .$this->settings['client_key']);
			$return = $this->requestManager->send();
			if($return->message == 'success'){
				$message = "success";
			} else {
				$message = "failed";
			}
		}
		echo $message;
		die();
		//$this->load->view('lightbox_header');
		//$this->load->view('edit_dependent',$data);
		//$this->load->view('lightbox_footer');
		
		
	}
	public function education($user_id = 0){
		$data = array();
		$data['user_id'] = ($user_id < 1) ? $this->input->post('user_id'):$user_id;
		if($this->input->post()){
			$data['education']= array('school_name' => $this->input->post('school_name'),
			'course_name' => $this->input->post('course_name'),
			'date_start' => $this->input->post('date_start'),
			'date_end' => $this->input->post('date_end'),
			'type' => $this->input->post('type'),
			'id' => $this->input->post('id'));
			$data['user_id'] = $this->input->post('user_id');
			
			$params['data'] = urlencode(ObjectUtils::arrayToJSON($data));

			$this->requestManager->setData($params);
			$this->requestManager->setSendType("post");
			$this->requestManager->setAccessPath($this->settings['api_path']."user/education/" .$this->settings['client_key']);
			$return = $this->requestManager->send();
			//var_dump($return);
			if($return->message == 'success'){
				$data['method'] = $this->input->post('method');				//}
				$data['message'] = "Education successfully added!";
				$data['education_id'] = $return->id;
				//$data['education'] = urlencode(ObjectUtils::arrayToJSON($data['education']));
			}

		} 
		
		$this->load->view('lightbox_header');
		$this->load->view('education',$data);
		$this->load->view('lightbox_footer');
	}
	
	public function delete_education(){
		$data = array();
		if($this->input->post()){
			$params = array('user_id' => $this->input->post('user_id'),
				'id' => $this->input->post('id'));
			
			$this->requestManager->setData($params);
			$this->requestManager->setSendType("rest");
			$this->requestManager->setAccessPath($this->settings['api_path']."user/delete_education/" .$this->settings['client_key']);
			$return = $this->requestManager->send();
			if($return->message == 'success'){
				$message = "success";
			} else {
				$message = "failed";
			}
		}
		echo $message;
		die();
		//$this->load->view('lightbox_header');
		//$this->load->view('edit_dependent',$data);
		//$this->load->view('lightbox_footer');
		
		
	}
	
	public function edit_education($user_id, $id){
		if(is_numeric($user_id) && is_numeric($id)){
			if($this->input->post()){
				$data['education']= array('school_name' => $this->input->post('school_name'),
				'date_start' => $this->input->post('date_start'),
				'date_end' => $this->input->post('date_end'),
				'type' => $this->input->post('type'),
				'id' => $this->input->post('id'));
				$data['user_id'] = $this->input->post('user_id');
				
				$params['data'] = urlencode(ObjectUtils::arrayToJSON($data));
	
				$this->requestManager->setData($params);
				$this->requestManager->setSendType("post");
				$this->requestManager->setAccessPath($this->settings['api_path']."user/education/" .$this->settings['client_key']);
				$return = $this->requestManager->send();
				$method = 'update';
			} else {
				$params = array('user_id'=>$user_id, 'id'=>$id );
				$this->requestManager->setData($params);
				$this->requestManager->setSendType("rest");
				$this->requestManager->setAccessPath($this->settings['api_path']."user/get_education/" .$this->settings['client_key']);
				$method = 'edit';
			}

			$return = $this->requestManager->send();
			//var_dump($return);
			if($return->message == 'success'){
				if($method == 'edit')
					$data['education'] = $return->data;	
				elseif($method == 'update'){
					$data['message'] = "Education successfully updated!";
					//var_dump($data['dependents']);
					
					//$data['dependent'] = $data['dependents'];
					
				}
			}
			$data['user_id'] = $user_id;
			$data['eduId'] = $this->input->post('id');
			$data['method'] = $method;
		}
		
		$this->load->view('lightbox_header');
		$this->load->view('education',$data);
		$this->load->view('lightbox_footer');
		
	}
	
	public function employment($user_id=0,$id=0){
		$data = array();
		$data['user_id'] = ($user_id < 1) ? $this->input->post('user_id'):$user_id;
		if($this->input->post()){
			$data['employment']= array('employer_name' => $this->input->post('employer_name'),
			'id' => $this->input->post('id'),
			'position' => $this->input->post('position'),
			'description' => $this->input->post('description'),
			'date_start' => $this->input->post('date_start'),
			'date_end' => $this->input->post('date_end'));

			$data['user_id'] = $this->input->post('user_id');			
			$params['data'] = urlencode(ObjectUtils::arrayToJSON($data));

			$this->requestManager->setData($params);
			$this->requestManager->setSendType("post");
			$this->requestManager->setAccessPath($this->settings['api_path']."user/employment/" .$this->settings['client_key']);
			$return = $this->requestManager->send();
			if($return->message == 'success'){
				$data['method'] = $this->input->post('method');	
				$data['employment_id'] = $return->id;
				switch($data['method']){
					case 'update':
						$label = 'updated!';
						break;
					case 'add':
						$label	=	'added!';
						break;
					
				}
				$data['message'] = "Employment successfully " . $label;
			}

		}else if($user_id >0 && $id > 0){
			
			$params = array('user_id'=>$user_id, 'id'=>$id );
			$this->requestManager->setData($params);
			$this->requestManager->setSendType("rest");
			$this->requestManager->setAccessPath($this->settings['api_path']."user/get_employment/" .$this->settings['client_key']);
			$method = 'edit';
			$return = $this->requestManager->send();
			if($return->message == 'success'){
				$data['employment'] = $return->data;	
				$data['method'] = "edit";	
			}
			
		}
		
		$this->load->view('lightbox_header');
		$this->load->view('employment',$data);
		$this->load->view('lightbox_footer');
	}
	
	public function edit_employment($user_id, $id){
		if(is_numeric($user_id) && is_numeric($id)){
			$this->employment($user_id, $id);
		}
	}
	
	public function delete_employment(){
		$data = array();
		if($this->input->post()){
			$params = array('user_id' => $this->input->post('user_id'),
				'id' => $this->input->post('id'));			
			$this->requestManager->setData($params);
			$this->requestManager->setSendType("rest");
			$this->requestManager->setAccessPath($this->settings['api_path']."user/delete_employment/" .$this->settings['client_key']);
			$return = $this->requestManager->send();
			if($return->message == 'success'){
				$message = "success";
			} else {
				$message = "failed";
			}
		}
		echo $message;
		die();
	
	}
	
	public function contributions(){
		$data = array();
		
		if($this->input->post()){		
			$params['data'] = urlencode(ObjectUtils::arrayToJSON($this->input->post()));
			$this->requestManager->setData($params);
			$this->requestManager->setSendType("post");
			$this->requestManager->setAccessPath($this->settings['api_path']."user/contributions/" .$this->settings['client_key']);
			$return = $this->requestManager->send();
			//var_dump($return);
			if($return->message == 'success'){
				$message = "Contributions successfully saved!";
			} else {
				$message = "failed";
			}
		}
		
		echo $message;
		die();
	}
	
	public function deductions(){
		$data = array();
		if($this->input->post()){
			
		}
		echo "Data saved!";
		die();
	}

}